//
//  DBRefreshControl.swift
//  大波微博swift
//
//  Created by 大波 on 16/3/8.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit

class DBRefreshControl: UIRefreshControl {
    
    // 触发刷新的偏移值
    let refreshOffset: CGFloat = -60
    
    // 图片是否向上标识符
    var isUp: Bool = false

    override var frame: CGRect {
        
        didSet {
            
//            print("frame: \(frame)")
            
            let refreshY = frame.origin.y
            
            if refreshY > 0 {
                
                return
            }
            
            if refreshY <= refreshOffset && isUp == false {
            
                isUp = true
        
                refreshView.rotationTipIcon(isUp)
                
            } else if refreshY > refreshOffset && isUp == true {
                
                isUp = false
                
                refreshView.rotationTipIcon(isUp)
            }
            
            if refreshing {
                
                refreshView.beginLoadIconAnimate()
            }
        }
    }
    
    override init() {
        
        super.init()
        
        prepareUI()
    }
    
    override func endRefreshing() {
        
        super.endRefreshing()
        
        refreshView.endLoad()
    }
    
    private func prepareUI() {
        
        addSubview(refreshView)
        
        refreshView.snp_makeConstraints { (make) -> Void in
            
            make.size.equalTo(refreshView.bounds.size)
            
            make.centerX.centerY.equalTo(self)
        }
        
        print("refreshViewFrame: \(refreshView.frame)")
    }
    
    // MARK: - 懒加载
    
    /// 从xib加载的refreshView
    private lazy var refreshView: DBRefreshView = DBRefreshView.loadRefresh()

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
